﻿using Masuit.Tools.AspNetCore.ModelBinder;
using Masuit.Tools.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebService.Authorize;
using WebService.EF;
using WebService.Models;
using YaseiAkira.AJ.Util;

namespace WebService.Controllers.System
{
    /// <summary>
    /// 后台账户相关接口
    /// </summary>
    [ApiController]
    [ApiExplorerSettings(GroupName = "system")]
    [Route("system/[controller]/[action]")]
    [AJAuthorize]
    public class AccountController : Controller
    {
        private DbService db;
        public AccountController(DbService dbIns)
        {
            db = dbIns;
        }

        /// <summary>
        /// 后台账户登录
        /// </summary>
        /// <param name="data">登录表单</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ObjectResult> Login(CommonLoginModel data)
        {

            if (data == null || string.IsNullOrWhiteSpace(data.account) || string.IsNullOrWhiteSpace(data.password))
            {
                Util.FriendlyError("账户名或密码未提交");
            }

            var account = data.account;


            data.password = data.password.AESEncrypt(Properties.Resources.AesKey);

            var password = data.password;

            var user = await db.SystemUsers
                .Where(x => x.AccountName == account && x.Password == password)
                .FirstOrDefaultAsync();

            if (user == null)
            {
                Util.FriendlyError("账户名或密码错误");
            }

            if (!user.Enable)
            {
                Util.FriendlyError("账户已禁用");
            }

            return new ObjectResult(new
            {
                token = Util.CreateAuthToken(user.Id, (int)IdentityType.System, DateTime.Now.AddMinutes(30).Ticks)
            });
        }
    }
}
